package com.htdata.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class JsonUtil {
	// 根据json文件生成property文件
	public void createPropertyByJson() throws IOException {
		// 读取device文件并按新要求存储到property文件
		ArrayList<String> list = new ArrayList<String>();
		BufferedReader br = null;
		BufferedWriter bw = null;
		// 读取原始json文件并进行操作和输出
		try {
			String path = this.getClass().getClassLoader().getResource("").getPath();
			File file = new File(path+"com/htdata/jsondata");
			// json下文件个数
			File[] fileList = file.listFiles();
			
			if (fileList.length > 0) {
				for (int i = 0; i < fileList.length; i++) {
					// 读取原始json文件
					br = new BufferedReader(new InputStreamReader(new FileInputStream(fileList[i]), "utf-8"));
					JsonParser parser=new JsonParser();
					JsonObject object=(JsonObject) parser.parse(new FileReader(fileList[i]));
					// 输出新的json文件
					bw = new BufferedWriter(new FileWriter("/load.properties",true));
					String s = null, ws = null;
					String str= "";
					while ((s = br.readLine()) != null) {
						System.out.println(s);
						str += s;
					}
					System.out.println(str);
						try {
							JSONObject dataJson = new JSONObject(str);// 创建一个包含原始json串的json对象
							//iot信息
							String iot = ((JSONObject)dataJson.getJSONObject("iotmsg")).getString("iot");
							String accesskey = ((JSONObject)dataJson.getJSONObject("iotmsg")).getString("accesskey");
							//设备数组
							JSONArray devInfo = dataJson.getJSONArray("equipmentmasg");
							//String equipmentStr = 
							for (int j = 0; j < devInfo.length(); j++) {
								// 获取devInfo数组的第i个json对象
								JSONObject info = devInfo.getJSONObject(j);
								String equipment = info.getString("equipment");// 读取properties对象里的name字段值
								System.out.println(equipment);
							}
						//	System.out.println(ws);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
					//bw.write(ws);
					//bw.flush();
				}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				br.close();
			}
			if (bw != null) {
				bw.close();
			}
		}
	}
}
